﻿// 源文件头信息：
// <copyright file="SearchParam.cs">
// Copyright(c)2012-2019.
// CLR版本：4.0.30319.239
// 开发组织：luochengbang@163.com
// 公司网站：
// 所属工程：Janus.Cores.Repository.Tools
// 最后修改：Ben.Luo
// 最后修改：2013/05/14 23:04
// </copyright>

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Linq.Dynamic;

namespace Janus.BaseEntitys
{
    [Serializable]
    /// <summary>
    /// 通用搜索参数类
    /// </summary>
    public class SearchEntity<TEntity> where TEntity : Entity, new()
    {
        public SearchEntity(Expression<Func<TEntity, bool>> predicate, PaginationDTO pagination)
        {
            if (predicate != null)
            {
                var pstr = predicate.ToString();
                if (!string.IsNullOrEmpty(pstr))
                {
                    var op = predicate.Parameters[0].Name + ".";
                    this.PredicateStr = pstr.Substring(pstr.IndexOf("=>")).Replace("=>", "").Replace(op, "").Replace("AndAlso", "&&").Replace("OrElse", "||");
                    //this.PredicateStr = "(IndicatorName.StartsWith(\"SaveMany\") AndAlso (IndicatorValue > 1))";
                }
            }
            Pagination = pagination;            
        }

        /// <summary>
        /// 获取搜索条件
        /// </summary>
        public Expression<Func<TEntity, bool>> GetPredicate()
        {
            if (!string.IsNullOrEmpty(this.PredicateStr))
            {
                var e1 = System.Linq.Dynamic.DynamicExpression.ParseLambda<TEntity, bool>(this.PredicateStr);
                return e1;
            }
            else
            {
                return null;
            }
        }

        public SearchEntity<TEntity> OrderBy(Expression<Func<TEntity, object>> order)
        {
            var member = GetMemberExpression(order);
            var name = member.Member.Name;
            this.Orders += string.Format("{0} ASC", string.IsNullOrEmpty(this.Orders) ? "ORDER BY [" + name + "]" : ",[" + name + "]");
            return this;
        }

        public SearchEntity<TEntity> OrderDescBy(Expression<Func<TEntity, object>> order)
        {
            var member = GetMemberExpression(order);
            var name = member.Member.Name;
            this.Orders += string.Format("{0} DESC", string.IsNullOrEmpty(this.Orders) ? "ORDER BY [" + name + "]" : ",[" + name + "]");
            return this;
        }

        /// <summary>
        /// 搜索条件
        /// </summary>
        public string PredicateStr
        {
            get; private set;
        }

        public string Orders
        {
            get; private set;
        }

        PaginationDTO _Pagination = new PaginationDTO();
        /// <summary>
        /// 分页信息
        /// </summary>
        public PaginationDTO Pagination
        {
            get { return _Pagination; }
            set { _Pagination = value; }
        }

        private MemberExpression GetMemberExpression(Expression expression)
        {
            if (expression == null)
                return null;
            switch (expression.NodeType)
            {
                case ExpressionType.Lambda:
                    return GetMemberExpression(((LambdaExpression)expression).Body);
                case ExpressionType.Convert:
                    return GetMemberExpression(((UnaryExpression)expression).Operand);
                case ExpressionType.Equal:
                case ExpressionType.NotEqual:
                case ExpressionType.GreaterThan:
                case ExpressionType.LessThan:
                case ExpressionType.GreaterThanOrEqual:
                case ExpressionType.LessThanOrEqual:
                    return GetMemberExpression(((BinaryExpression)expression).Left);
                case ExpressionType.Call:
                    return GetMemberExpression(((MethodCallExpression)expression).Object);
                case ExpressionType.MemberAccess:
                    return (MemberExpression)expression;
            }
            return null;
        }
    }

    //[Serializable]
    //public class SearcherEntity
    //{
    //    private List<Orders> hasOrders = new List<Orders>();
    //    /// <summary>
    //    /// 排序字段（多表时需带表名）分页时必须指定
    //    /// [key:column,value:Asc or Desc]
    //    /// </summary>
    //    public List<Orders> HasOrders
    //    {
    //        get { return hasOrders; }
    //        set { hasOrders = value; }
    //    }

    //    private List<Conditions> listWheres = new List<Conditions>();
    //    /// <summary>
    //    /// 搜索条件（多表时需带表名）
    //    /// </summary>
    //    public List<Conditions> ListWheres { get { return listWheres; } set { listWheres = value; } }

    //    /// <summary>
    //    /// 查询表名(多个表名可用逗号分隔，也可使用Join连接)
    //    /// </summary>
    //    public string TableName { get; set; }

    //    /// <summary>
    //    /// 指定判断Table别名
    //    /// </summary>
    //    public string AliasTableName { get; set; }

    //    //private string joinWhere = string.Empty;
    //    ///// <summary>
    //    ///// --join条件
    //    ///// </summary>
    //    //public string JoinWhere
    //    //{
    //    //    get { return joinWhere; }
    //    //    set { joinWhere = value; }
    //    //}

    //    /// <summary>
    //    /// 查询字段(多表时需带表名)
    //    /// </summary>
    //    public string SearchFields { get; set; }

    //    /// <summary>
    //    /// 排序字段（多表时需带表名）
    //    /// Cols1 Asc,Cols2 Desc
    //    /// </summary>
    //    public string OrderCols { get; set; }

    //    ///// <summary>
    //    ///// 排序方式
    //    ///// </summary>
    //    //private string orderType = "0";
    //    //public string OrderType
    //    //{
    //    //    get { return orderType; }
    //    //    set { orderType = value; }
    //    //}

    //    private bool isPaging = true;
    //    /// <summary>
    //    /// 是否分页(默认分页)
    //    /// </summary>
    //    public bool IsPaging { get { return isPaging; } set { isPaging = value; } }
    //}

    ///// <summary>
    ///// 排序
    ///// </summary>
    //[Serializable]
    //public class Orders
    //{
    //    public string ColumnName { get; set; }
    //    public string OrderType { get; set; }

    //    private List<Orders> orderList = new List<Orders>();
    //    public List<Orders> ToList
    //    {
    //        get { return orderList; }
    //        set { orderList = value; }
    //    }

    //    public void Add(string columnName, string orderType)
    //    {
    //        orderList.RemoveAll(c => c.ColumnName == columnName);
    //        orderList.Add(new Orders() { ColumnName = columnName, OrderType = orderType });
    //    }

    //    public void AddRange(IList<Orders> orders)
    //    {
    //        orderList.AddRange(orders);
    //    }

    //    public Orders Find(string columnName)
    //    {
    //        return orderList.FirstOrDefault(c => c.ColumnName == columnName);
    //    }

    //    public void Remove(string columnName)
    //    {
    //        orderList.RemoveAll(c => c.ColumnName == columnName);
    //    }


    //    public Orders this[int i]
    //    {
    //        get
    //        {
    //            return orderList[i];
    //        }
    //        set
    //        {
    //            orderList.Add(value);
    //        }
    //    }
    //    public Orders this[string columnName]
    //    {
    //        get
    //        {
    //            var orders = orderList.FirstOrDefault(c => c.ColumnName == columnName);
    //            return orders;
    //        }
    //        set
    //        {
    //            orderList.Add(value);
    //        }
    //    }
    //}
}
